/**
 * Created by seeker910 on 2017/5/5.
 * @description 自定义展示元素的 批量数据编辑保存，不包含sechma属性
 */ 
 Rsd.define('Rsd.zen.dialog.ListViewDialog', {
    extend: 'Rsd.container.Dialog',
    requires: [ 
        'Rsd.control.ListView',
        'Rsd.control.SearchToolBar',
        'Rsd.control.PagingBar'
    ],
    xtype: 'list-view-dailog',
    border: false,
    tabTitle: 'Title',
    layout: 'vbox',
    selected:true,
    /**
     * @description 是否分页显示
    * */
    pagging:true,
    /**
     * 
     */
    items:[
        {
            xtype:'search-tool-bar',
            label:false,
            //region:'top',
            searchHandler:'searchListData',
            cls: 'x-header',
            style:{minHeight:50},
            height:60
        },
        {
            xtype: 'list-view',
            //region:'center',
            label:false,
            flex:1,
            margin: '0 1 5 0',
            itemXtype:'label', 
            itemDblClick: 'list_item_dblclick',
            itemClick:''
        },
        {
            xtype:'paging-bar',
            label:false,
            margin:'0 0 0 0',
            indexChanged:'pageIndexChanged',
            style:{backgroundColor: 'lightsteelblue'},
            region:'bottom',
            height:40
        }
    ],
    /**
     * @description 元素对象控件类型
     */
    //itemXtype:'',
    /**
     * @description 元素对象控件样式
     */
    //itemStyle:{},
    /**
     * 
     */
    itemDblClick:'',
    /**
     * 
     */
    form:{
        viewType:'Rsd.zen.dialog.FormDialog',
        title:'',
        height:'80%',
        width:'60%',
        buttons:null
    }, 
    /*
    * */
    //formFields:[],
     /**
     * @description 优先级排第一
     * @description 获取数据源的 服务名 优先使用serviceName ,获取到的Service 将作为dataStore的proxy属性值
     */
      serviceName:null,
      /**
       * @description 优先级排第二
       * @description Rsd.data.Store数据源，支持本地数据已本地缓存数据
       *  @description 在serviceName有效时，该属性将自动创建为 new Rsd.data.Store({proxy:app.getService(serviceName),listName:listMember})
       */
      dataStore:null,
      /**
       * @description 在serviceName有效时，listMember将作为dataStore的listName属性值
       */
      listMember:null,
      /**
       * item 被选中时 事件
       */
      OnItemSelected:null,
    /*
    * */
    constructor: function ListViewPage(config) {
        config = config || {};
        this.apply(config); 
    }, 
    /**
     * 
     */
    onBeforeInit:function onBeforeInit()
    {
        if(this.menu)
        {
            this.readonly = this.menu.readonly == undefined ? this.readonly : this.menu.readonly;
            this.modelType = this.modelType || this.menu.modelType;
            this.serviceName =  this.serviceName || this.menu.serviceName; 
            this.listMember = this.listMember || this.menu.listMember || 'rows';
            this.where = Rsd.arrayConcat(this.where || [],this.menu.where||[]);
            this.sort = Rsd.arrayConcat(this.sort ||[], this.menu.sort||[]);

            this.searchColumns = Rsd.arrayConcat(this.searchColumns ||[], this.menu.searchColumns||[]);
            this.newButtons = Rsd.arrayConcat(this.newButtons||[],this.menu.newButtons||[]); 

            this.titleField =  this.titleField || this.menu.titleField || '';
            this.titleMember = this.titleMember || this.menu.titleMember || '';

            if(this.menu.formTitle)
            {
                this.form.title = this.menu.formTitle;
            }
            if(this.menu.formModelType)
            {
                this.form.modelType = this.menu.formModelType;
            }
        }
        

        //4.* 版本下，监控；下一个版本取消
        if(Rsd["version"].startWith('4.'))
        {
            if(this.formViewType)
            {
                this.form.viewType = this.formViewType;
                console.error('formViewType属性已取消，请使用form:{viewType:"XXXX"}方式代替');
            }
            if(this.formModelType)
            {
                this.form.modelType = this.formModelType;
                console.error('formModelType属性已取消，请使用form:{modelType:"XXXX"}方式代替');
            }
            if(this.formTitle)
            {
                this.form.title = this.formTitle;
                console.error('formTitle属性已取消，请使用form:{title:"XXXX"}方式代替');
            }
            if(this.titleField)
            {
                this.form.titleField = this.titleField;
                console.error('titleField属性已取消，请使用form:{titleField:"XXXX"}方式代替');
            }
            if(this.formFieldWidth)
            {
                this.form.fieldWidth = this.formFieldWidth;
                console.error('formFieldWidth属性已取消，请使用form:{fieldWidth:"45%"}方式代替');
            } 
            if(this.formHeight)
            {
                this.form.height = this.formHeight;
                console.error('formHeight属性已取消，请使用form:{height:"XXXX"}方式代替');
            }
            if(this.formWidth)
            {
                this.form.width = this.formWidth;
                console.error('formWidth属性已取消，请使用form:{width:"XXXX"}方式代替');
            }
            if(this.formData)
            {
                this.form.data = this.formData;
                console.error('formData属性已取消，请使用form:{data:{}}方式代替');
            } 
            if(this.formPosition)
            {
                this.form.position = this.formPosition;
                console.error('formPosition属性已取消，请使用form:{position:"XXXX"}方式代替');
            }
            if(this.formButtons)
            {
                this.form.buttons = this.formButtons;
                console.error('formButtons属性已取消，请使用form:{buttons:[]}方式代替');
            }
        } 
        this.callParent();
    },
    /**
    *
    * */
     onBeforeRender: function onBeforeRender() {

        this.menu = this.menu || {};
        //debugger;

        this.modelType = this.modelType || this.menu.modelType;
        this.titleField = this.titleField || this.menu.titleField;
      
        var columns = this.searchColumns || [];
        var _list = [];
        for (var i in columns) {
            var _c = columns[i]; 
            _c.margin = _c.margin || "0 0 0 20";
            _list.push(_c)

        }
       
        this.toolBar.searchColumns = _list;

        var btns = this.newButtons || [];
         
        this.toolBar.newButtons = btns;

        this.callParent();

        return this;
    },
    /*
     * */
    pageIndexChanged: function pageIndexChanged(pagingOpt) {
        //debugger;

        this.load({});//只需重新加载，pagingOpt 信息自动获取

    },
    /*
    *
    * */
    searchListData:function searchListData(where) {

        var me = this;
        var _args = {};
        if(!Rsd.isEmpty(where))
        {
            _args.where=where;
        }
        this.load(_args);
    },
    /*
     args :api 接口需要的参数
    *
    * */
    load:function load(args,callback) {
        
        this.callParent();
        //debugger;
        var me = this;
        var listView = me.items[1];
        if(!(listView instanceof Rsd.control.ListView))
        {
            console.error("me.items[1] is not Rsd.control.ListView");
        }
        Rsd.showWaiting(me.id, listView);
         if(!me.dataStore)
         {
                var _serviceName = this.serviceName||this.menu.serviceName;
                if(!Rsd.isEmpty(_serviceName))
                {  
                    var _service = Rsd.app.getService(_serviceName);
                    if(_service)
                    {
                        this.dataStore = Rsd.create('Rsd.data.Store',{proxy:_service,listName:this.listMember||this.menu.listMember||'rows'});
                    }
                
                }
         }
         
        if(me.dataStore)
        {
            listView.dataSource = me.dataStore;
        }
        
        setTimeout(function () {
            //console.log(args);console.log(opt);console.log(_args);
            var opt  = me.getPagingOpt();
            var _args = args || {};
            me.____lastWhere = me.getWhere();
            _args = Rsd.apply(_args, {
                modelType: me.modelType,
                where: Rsd.arrayConcat(_args.where || [],me.where, me.menu.where, me.____lastWhere),
                sort: Rsd.arrayConcat(_args.sort || [],me.sort, me.menu.sort),
                pageSize:opt.pageSize,
                pageIndex:opt.pageIndex
            });

            listView.removeAll();
            listView.loadData(_args, function (data) {
 
                if(data && data.success)
                {
                    var _data = data.data||{};
                    if(Rsd.isArray(_data))
                    {
                        me.setPagingOpt({pageSize:opt.pageSize,pageIndex:0,pageCount:1,totalCount:_data.length});
                    }
                    else
                    {
                        me.setPagingOpt({pageSize:_data.pagesize,pageIndex:_data.pageindex,pageCount:_data.pagecount,totalCount:_data.total});
                    }
                }

                var _f = Rsd.callFunction(me, callback||function (__data) {

                    if(__data===undefined || __data === null)
                    {
                        Rsd.alert('数据加载失败', '未获取到数据（网络故障）。');
                        return false;
                    }
                    if(Rsd.isArray(__data))
                    {
                        return true;
                    }
                    if(__data.success)
                    {}
                    else
                    {

                        if(Rsd.isEmpty(__data.msg))
                        { 
                            console.error('未知错误(UI0009),请查看日志。',resp);
                        }
                       
                        return true;
                    }

                    return true;

                }, arguments);

                Rsd.closeWaiting(me.id);
                //console.log('BaseListPage.loadData return: ' + _f);
                return _f;
            });

        }, 50);

    },

    /**
    * @description 获取分页信息,在查询时，自动加上分页信息
    * */
    getPagingOpt:function getPagingOpt() {
        
      if(this.items[2] instanceof  Rsd.control.PagingBar)
      {
          return this.items[2].getPaging();
      }
      return {};
    },

    /**
    * @description 设置分页信息,一般在查询条件发发生改变时，需重新设置分页 {pageIndex: 0}
    * */
    setPagingOpt:function setPagingOpt(opt) {

        if(this.items[2] instanceof  Rsd.control.PagingBar)
        {
            return this.items[2].setPaging(opt);
        }
    },
    
     
    /*
    * */
    list_item_dblclick:function list_item_dblclick(item,evt)
    {
        this.funApplyByIOC(this.itemDblClick,[item.content,evt]);
    },

    /**
     * @description 展示详细信息
     * @param {*} row 
     * @param {*} readonly 
     */
    showItem:function showItem(row,readonly)
      {
          var _record=row;
           
          var _titleField = this.form.titleField || this.titleMember || this.menu.titleField || this.menu.titleMember||this.modelSchema.titleField;
          var _formTitle = this.form.title || (_titleField == null || _titleField.length == 0) ? "明细[titleField未设置]" : ("明细["+(_record ? (_record[_titleField] || '-') : '*')+"]");
          var _title = Rsd.template(_formTitle,_record||{});
           
          var form = Rsd.create(this.form.viewType, {
             
              formFields:this.formFields?.length>0?this.formFields:(this.modelSchema.fields||[]),
              buttons:this.form.buttons||['save','cancel'],
              modelSchema:this.modelSchema,
              parent:this,
              readonly:readonly,
              title: _title,
              height:this.form.height||500,
              width:this.form.width||480,
              data:row
          });
  
          form.showDialog();
    },
    
    /**
     * 
     */
    btn____search:function btn____search() {

        //友好做法时：在查询条件发发生改变时，设置分页 {pageIndex: 0}
        if(this.whereIsChange())
        {
            this.setPagingOpt({pageIndex:0});
        }

        this.load({});
    },
    /**
   * */
    getWhere:function getWhere(){

        var _c = [];
        var _default =  this.toolBar;
        for(var i in this.searchColumns) {
            var _item = this.searchColumns[i];
            var _ctrl = _default.getItemByName(_item.name);
            var _value = _ctrl.getValue();
            if (_value == null || _value == '') {
                continue;
            }
            _value = _value.trim();
            var _op =  _item.op;

            if (Rsd.isEmpty(_item.op) ) {

                _op =  'like';
            }
            if(_value.lastIndexOf(',')>0)
            {
                _value = _value.split(',');
            }
            if( _op == 'like')
            {
                if(Rsd.isArray(_value))
                {
                    var _temp = [];
                    for(var i in _value)
                    {
                        var v = _value[i];
                        if(Rsd.isEmpty(v))
                        {
                            continue;
                        }
                        _temp.push('%25' + v.trim() + '%25');
                    }
                    _value = _temp;
                }
                else
                {
                    _value = '%25' + _value.trim() + '%25';
                }

            }

            if(_ctrl instanceof Rsd.form.CheckBox )
            {
                if(!_ctrl.isChecked())
                {
                    continue;
                }
            }


            var _dataIndex = _item.dataIndex || _item.name || _item.key;
            if (Rsd.isArray(_dataIndex))
            {
                for(var i in _dataIndex)
                {
                    if(Rsd.isEmpty(_dataIndex[i]))
                    {
                        continue;
                    }
                    _c.push({group:_item.group||_item.name||'defualt',name:_dataIndex[i],value:_value,op:_op,logic:(i==0)?'none':'or'});
                }
            }
            else
            {
                if (_op.toLowerCase() == 'isnull' || _op.toLowerCase()  == 'isnotnull' ) {

                    _c.push({name:_dataIndex,op:_op});
                }
                else
                {
                    _c.push({name:_dataIndex,value:_value + '',op:_op});
                }


            }

        }

        return _c;
    },
    /**
    * */
    whereIsChange:function whereIsChange() {

        var _where = this.getWhere();
        if (Rsd.isEmpty(this.____lastWhere) && Rsd.isEmpty(_where)) {
            return false;
        }
        if (Rsd.isEmpty(this.____lastWhere) || !Rsd.isEmpty(_where)) {
            return true;
        }
        if (!Rsd.isEmpty(this.____lastWhere) || Rsd.isEmpty(_where)) {
            return true;
        }
        if (this.____lastWhere.length  != _where.length) {
            return true;
        }
        for(var i in _where)
        {

        }
        return true;
    },
    /**
     * 本也表格数据导出excel
     * @param {*} sheet 
     * @param {*} file 仅文件名称（不是路径）
     */
    "export": function _export(sheet,file) {
        var grid = this.items[0];
        grid.export(sheet,file);
    }


},function(type){

 
   //toolbar
    var _toolBarGetter = function () {

        if(this.items.length ==0)
        {
            return null;            
        }
        return this.items[0]; 
    };

    var _toolBarSetter = function (value) {

        if(Rsd.isString(value))
        {
            this.items[0].xtype = value;
            return;
        }

        if(Rsd.isObject(value) ) {
            Rsd.apply(this.items[0], value);
            return;
        }
    }

    this.defineProperty(type,"toolBar", _toolBarGetter, _toolBarSetter,false);

    //footbar
    var _footBarGetter = function () {

        return this.items[2];
    };

    var _footBarSetter = function (value) {

        this.items[2] = value;

        if(Rsd.isObject(value) && !value.hasOwnProperty('xtype'))
        {
            this.items[2].xtype = 'paging-bar';
        }

    }

    this.defineProperty(type,"footBar", _footBarGetter, _footBarSetter,false);

    //itemXtype 
    this.defineProperty(type,"itemXtype", function(){return this.items[1].itemXtype;}, function(value){return this.items[1].itemXtype=value;},false);
    //itemStyle 
    this.defineProperty(type,"itemStyle", function(){return this.items[1].itemStyle;}, function(value){return this.items[1].itemStyle=value;},false);

 
    var _newButtonsGetter = function () {

        if(!Rsd.isEmpty(this.__newButtons))
        {
            return this.__newButtons;
        }
        if(this.readonly)
        {
            return [{xtype:'button', text: '加 载' ,visible:true,margin: '0 5 0 10', width: 100, handler:'btn____search'}];
             
        }else
        {
            return [{xtype:'button', text: '加 载' ,visible:true,margin: '0 5 0 10', width: 100, handler:'btn____search'},{text:'新 增',handler:'newItem'}];
        } 
    };

    var _newButtonsSetter = function (value) {
        var _value = value||[];
        for(var i in _value)
        {
            _value[i] = Rsd.apply({margin: '0 5 0 10'},_value[i]);
        }
        this.__newButtons = Rsd.arrayConcat([{xtype:'button', text: '加 载' ,visible:true,margin: '0 5 0 10', width: 100, handler:'btn____search'}],_value);
    }

    this.defineProperty(type,"newButtons", _newButtonsGetter, _newButtonsSetter,true);


    var _searchColumnsGetter = function _searchColumnsGetter() {

        return this.__searchColumns;
    }

    var _searchColumnsSetter = function _searchColumnsSetter(value) {

        this.__searchColumns = value;
    }

    this.defineProperty(type,"searchColumns", _searchColumnsGetter, _searchColumnsSetter,true);

    //
    var _formGetter = function _formGetter()
    {
        if(Rsd.isEmpty(this.__form))
        {
            this.__form = {
                viewType:'Rsd.zen.dialog.FormDialog',//明细窗体类型
                modelType:this.modelType,
                fields:null,
                fieldWidth:'45%',//form 字段默认宽度
                titleField:'',
                title:'',
                height:'auto',//form 窗体高度
                width:'60%', //form 窗体宽度
                position:'center', //表单展示位置 center,left,right  
                buttons:['save','delete','cancel'],//form 表单底部buttons
                data:{}//新增时 form默认数据 
            };
        }

       return this.__form;
    };

    var _formSetter  =function _formSetter(value)
    {
        if(Rsd.isString(value))
        {
            this.form.viewType = value;
            return;
        }
       
        if(Rsd.isObject(value))
        {
            Rsd.apply(this.form,value);
            return;
        }
        
    }

    this.defineProperty(type,"form", _formGetter, _formSetter,true);
      
});